using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Cinemachine;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Level : MonoBehaviour
{
    CinemachineConfiner confiner;
    public Collider2D origin;
    public int level=1;
    public LayerMask target;
	public List<Transform> saveTransforms = new List<Transform>();

    private void Awake()
    {
        if (confiner == null)
            confiner = GameObject.FindFirstObjectByType<CinemachineConfiner>();

        saveTransforms = GetComponentsInChildren<Transform>().ToList();

        PlayerData data = SaveManager.Instance.LoadPlayerData();
        if (!data.isInit)
        {
            data.isInit = true;
            data.Position = saveTransforms[1].position;
            data.Level = level;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if ((1 << collision.gameObject.layer & target) != 0 )
        {            
            if(origin is PolygonCollider2D)
                confiner.m_BoundingShape2D = origin;
            
            LevelManager.Instance.currentLevel = level;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
		if ((1 << collision.gameObject.layer & target) != 0 && !LevelManager.Instance.Restart)
        {
            if ((level<2))
            {                
                PlayerData data = SaveManager.Instance.LoadPlayerData();
                data.isInit = false;
                SceneManager.LoadScene(level+1);
            }
            else
            {
                SceneManager.LoadScene(0);
            }
        }
	}
}